﻿using CapWeb251.Models;
using Dapper;
using DotNetFramework.CAP;
using DotNetFramework.CAP.MySql;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CapWeb251.Controllers
{
    public class MysqlOperateController : ApiController
    {
        private readonly ICapPublisher _capBus;

        public MysqlOperateController()
        {
            _capBus = CapConfig.Services.ServiceProvider.GetRequiredService<ICapPublisher>();
        }

        public string Get(int id)
        {
            using (var connection = new MySqlConnection("Server=192.168.231.132;port=3306;database=CapDemo;user=root;password=123456;Pooling=True;Max Pool Size=500;Min Pool Size=5;"))
            {
                using (var transaction = connection.BeginTransaction(_capBus, autoCommit: false))
                {
                    //业务代码
                    string sql = $@"INSERT INTO UserEntity (UserName,Phone,Email,Gender) 
                                VALUES('XujkCAP251', '13586985632145', 'test@nxin.com', 1); ";


                    //这里的事务是指  发送消息和执行当前SQL一致性
                    connection.Execute(sql, transaction: (IDbTransaction)transaction.DbTransaction);

                    UserEntity model = new UserEntity() { UserName = "XujkCAP251" };
                    _capBus.Publish("cap251.services.insert.user", model, "callbackmysql-show-execute-time");

                    transaction.Commit();
                }
            }

            return "value:" + 123;
        }
    }
}
